package com.itfreer.content;

import android.database.sqlite.SQLiteDatabase;

import com.itfreer.content.notice.NoticeEntity;
import com.itfreer.content.task.TaskEntity;
import com.itfreer.utils.config.ConfigManager;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据库操作管理工具类
 */
public class GatherDatabaseHelper extends OrmLiteSqliteOpenHelper {

    // 数据库名称
    private static final String DATABASE_NAME = "gather.db";
    private static final int DATABASE_VERSION = 1;

    // 本类的单例实例
    private static GatherDatabaseHelper instance;

    // 存储APP中所有的DAO对象的Map集合
    private Map<String, Dao> daos = new HashMap<>();

    // 获取本类单例对象的方法
    public static synchronized GatherDatabaseHelper getInstance() {
        if (instance == null) {
            synchronized (GatherDatabaseHelper.class) {
                if (instance == null) {
                    instance = new GatherDatabaseHelper();
                }
            }
        }
        return instance;
    }

    // 私有的构造方法
    private GatherDatabaseHelper() {
        super(ConfigManager.getContext(), DATABASE_NAME, null, DATABASE_VERSION);
    }

    // 根据传入的DAO的路径获取到这个DAO的单例对象（要么从daos这个Map中获取，要么新创建一个并存入daos）
    public synchronized Dao getDao(Class clazz) throws SQLException {
        Dao dao = null;
        String className = clazz.getSimpleName();
        if (daos.containsKey(className)) {
            dao = daos.get(className);
        }
        if (dao == null) {
            dao = super.getDao(clazz);
            daos.put(className, dao);
        }
        return dao;
    }

    // 创建数据库时调用的方法
    @Override
    public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
        try {
            TableUtils.createTable(connectionSource, NoticeEntity.class);
            TableUtils.createTable(connectionSource, TaskEntity.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 数据库版本更新时调用的方法
    @Override
    public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
        try {
            TableUtils.dropTable(connectionSource, NoticeEntity.class, true);
            TableUtils.dropTable(connectionSource, TaskEntity.class, true);

            onCreate(database, connectionSource);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 释放资源
    @Override
    public void close() {
        super.close();
        for (String key : daos.keySet()) {
            Dao dao = daos.get(key);
            dao = null;
        }
    }
}
